package com.java.test;

import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteFunctionCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;

public class BscTokenSwap {

    private static final String BSC_RPC_URL = "https://bsc-dataseed2.ninicoin.io";
    private static final String PANCAKE_SWAP_ROUTER = "0x10ED43C718714eb63d5aA57B78B54704E256024E";
    private static final String USDT_CONTRACT = "0x55d398326f99059fF775485246999027B3197955";
    private static final String HTET_CONTRACT = "0xe5Ee39274A86034df862D6743eE481AcfFE34986"; // 替换为HTET的实际合约地址

    public static void main(String[] args) throws Exception {
        String privateKey = "0xc96bf39e17f01460531bc682393430aaa46554a5ac69ac6d2d199655cc2ccf56";
        BigDecimal amountToSwap = new BigDecimal("1");
        int slippageTolerance = 100;

        swapUSDTToHTET(privateKey, amountToSwap, slippageTolerance);
    }

    public static void swapUSDTToHTET(String privateKey, BigDecimal amount, int slippage) throws Exception {
        Web3j web3j = Web3j.build(new HttpServiceEx(BSC_RPC_URL));
        Credentials credentials = Credentials.create(privateKey);

        // 加载USDT合约
        ERC20 usdt = ERC20.load(USDT_CONTRACT, web3j, credentials, new DefaultGasProvider());

        BigInteger amountInWei = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();

        // 1. 授权
        TransactionReceipt approveReceipt = usdt.approve(PANCAKE_SWAP_ROUTER, amountInWei).send();
        System.out.println("授权交易哈希: " + approveReceipt.getTransactionHash());
        Thread.sleep(15000);

        String WBNB = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; // BSC上的WBNB合约
        // 2. 构建交换路径
        List<String> path = Arrays.asList(USDT_CONTRACT, HTET_CONTRACT);

        // 3. 加载Router合约
        PancakeRouter router = PancakeRouter.load(PANCAKE_SWAP_ROUTER, web3j, credentials,
                new StaticGasProvider(BigInteger.valueOf(100000000), BigInteger.valueOf(3000000)));

        long deadline = System.currentTimeMillis() / 1000 + 1200;

        // 4. 执行交换
        TransactionReceipt swapReceipt = router.swapExactTokensForTokens(
                amountInWei,
                BigInteger.ZERO,
                path,
                credentials.getAddress(),
                BigInteger.valueOf(deadline)
        ).send();

        System.out.println("交换交易哈希: " + swapReceipt.getTransactionHash());
        web3j.shutdown();
    }
}

